import { Column } from '@antv/g2plot'
import { useEffect, useState } from 'react'

const data = [
  {
    type: '家具家电',
    sales: 38
  },
  {
    type: '粮油副食',
    sales: 52
  },
  {
    type: '生鲜水果',
    sales: 61
  },
  {
    type: '美容洗护',
    sales: 145
  },
  {
    type: '母婴用品',
    sales: 48
  },
  {
    type: '进口食品',
    sales: 38
  },
  {
    type: '食品饮料',
    sales: 38
  },
  {
    type: '家庭清洁',
    sales: 38
  }
]

export const getRemFontSize = () =>
  Number(document.documentElement.style.fontSize.replace('px', ''))

const Line = () => {
  const [chart, setChart] = useState<null | Column>()
  useEffect(() => {
    const columnPlot = new Column('lineChart', {
      data,
      xField: 'type',
      yField: 'sales',
      autoFit: true,
      label: {
        // 可手动配置 label 数据标签位置
        position: 'middle', // 'top', 'bottom', 'middle',
        // 配置样式
        style: {
          fill: '#ffffff',
          opacity: 0.6,
          fontSize: getRemFontSize() * 1.25
        },
        layout: [
          // 柱形图数据标签位置自动调整
          { type: 'interval-adjust-position' },
          // 数据标签防遮挡
          { type: 'interval-hide-overlap' },
          // 数据标签文颜色自动调整
          { type: 'adjust-color' }
        ]
      },
      tooltip: {
        domStyles: {
          'g2-tooltip-title': {
            fontSize: '1rem'
          },
          'g2-tooltip-list-item': {
            fontSize: '1rem'
          }
        }
      },
      xAxis: {
        label: {
          autoHide: true,
          autoRotate: false,
          style: {
            fontSize: getRemFontSize() * 1.25
          }
        }
      },
      yAxis: {
        label: {
          style: {
            fontSize: getRemFontSize() * 1.25
          }
        }
      },
      meta: {
        type: {
          alias: '类别'
        },
        sales: {
          alias: '销售额'
        }
      }
    })

    columnPlot.render()
    setChart(columnPlot)
  }, [])

  useEffect(() => {
    window.addEventListener('resize', resize)
    resize() // 初始化

    return () => {
      window.removeEventListener('resize', resize)
    }
  }, [chart])

  const resize = () => {
    if (!chart) return
    chart.update({
      label: {
        style: {
          fontSize: getRemFontSize() * 1.25
        }
      },
      xAxis: {
        label: {
          style: {
            fontSize: getRemFontSize() * 1.25
          }
        }
      },
      yAxis: {
        label: {
          style: {
            fontSize: getRemFontSize() * 1.25
          }
        }
      }
    })
  }

  return (
    <div id={'lineChart'} style={{ height: '100vh', width: '100vw' }}></div>
  )
}

export default Line
